<?php
namespace app\manage\controller;

use app\manage\controller\Base;
use think\facade\Db;
use support\View;
use support\Request;
use app\model\ShuomingModel;

class ShuomingController extends Base
{
    public function index(Request $request)
    {
        $data=$request->get();
        if(!isset($data['key'])){
            $data['key']='';
        }
        View::assign('data', $data);
        $info=ShuomingModel::where('title', 'like', '%'.$data['key'].'%')
        ->order('id desc')
        ->paginate(['list_rows'=>10,'query'=>request()->all()]);

        View::assign('info', $info);
        View::assign('count1', $info->total());
        return view('shuoming/index');
    }
    public function ajax(Request $request)
    {
        $data=$request->post();
        $shuoming=new ShuomingModel();
        if ($data['type']=='shuoming_del') {
            if ($shuoming->destroy($data['id'])) {
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
        }
        if ($data['type']=='shuoming_all') {
            if ($shuoming->destroy($data['id'])) {
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
        }
		if($data['type']=='shuoming_start'){
			if($shuoming->where('id',$data['id'])->update(['isopen'=>1])){
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
		}
		if($data['type']=='shuoming_stop'){
			if($shuoming->where('id',$data['id'])->update(['isopen'=>0])){
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
		}
        return json(['code' => 0, 'message' => '失败']);
    }
    public function add(Request $request)
    {
        if (request()->method()=='POST') {
            $data=$request->post();
            $validate = new \app\manage\validate\ShuomingValidate;
            if (!$validate->check($data)) {
                return view_e($validate->getError());
            }
			
            if (!isset($data['is_tui'])) {
                $data['is_tui']=0;
            } else {
                $data['is_tui']=1;
            }
            if ($data['create_time']) {
                $data['create_time']=strtotime($data['create_time']);
            }else{
                unset($data['create_time']);
            }
            $file = $request->file('pic');
            if ($file && $file->isValid()  && $file->getSize() >0) {
                if(!in_array($file->getUploadExtension(), ['jpg','png','gif','webp','jpeg'])){return view_e('图片格式不正确');}
                if($file->getSize() > 5*1024*1024){return view_e('图片大小不能超过5M');}
                $path = '/shuoming/'.date("YmdHis").rand(10000,99999).session('uid', '0').'.'.$file->getUploadExtension();
                $file->move(public_path().$path);
                $data['pic']=$path;
            } else {
                if (isset($data['ti'])) {
                    preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $data["text"], $arr);
					$config=Db::name('config')->column('value', 'key');
					//压缩图片
					foreach ($arr[1] as $k=>$v) {
					    if (substr($v, 0, 4)!='http' and substr($v, 0, 2)!='//' and is_file(substr($v, 1))) {
					        $newarr=getimagesize(substr($v, 1));
						   if ($config["is_ya"] ==1 and $newarr[0] >$config["ya_w"]) {
						      $image = \think\Image::open(substr($v, 1));
						      $h=$config["ya_w"]*$newarr[1]/$newarr[0];
						      $image->thumb($config['ya_w'],$h)->save(substr($v, 1));
						   }
					    }
					}
                    foreach ($arr[1] as $k=>$v) {
                        if (substr($v, 0, 4)!='http' and substr($v, 0, 2)!='//' and is_file(substr($v, 1))) {
                            $newarr=getimagesize(substr($v, 1));
                            if ($newarr[0] >100 and $newarr[1] >100) {
                                //图片转移位置
                                if (!is_dir("storage/shuoming/".date("Ymd"))) {
                                    mkdir("storage/shuoming/".date("Ymd"),0777,true);
                                }
                                $newwei="storage/shuoming/".date("Ymd").'/'.basename(substr($v, 1));
                                $wo=copy(substr($v, 1), $newwei);
                                if ($wo) {
                                    $data['pic']='/'.$newwei;
                                }
                                break;
                            }
                        }
                    }
                }
            }
            
            $config=Db::name('config')->column('value', 'key');
            //设置缩率图
            if ($config['thumbnail']==1 and isset($data['pic'])) {
                if (isset($data['pic'])) {
                    $image = \think\Image::open(substr($data['pic'], 1));
                    //计算配置项
                    if (!$config['t_w']) {
                        $config['t_w']=300;
                    }
                    if (!$config['t_h']) {
                        $config['t_h']=$config['t_w'];
                    }
                    $image->thumb($config['t_w'], $config['t_h'])->save(substr($data['pic'], 1));
                }
            }
            //添加水印
            if ($config['watermark']==1) {
                preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $data["text"], $arr1);
                foreach ($arr1[1] as $k=>$v) {
                    if (substr($v, 0, 4)!='http' and substr($v, 0, 2)!='//') {
                        $image = \think\Image::open(substr($v, 1));
                        $image->text($config['shui_neirong'], dirname(__FILE__).'/FZXBSJW.TTF', $config['shui_zihao'], $config['shui_yanse'], $config['shui_weizhi'], -15)->save(substr($v, 1));
                    }
                }
            }
            if ($data['desc']=='') {
                $data['desc']=mb_substr(preg_replace('/\&nbsp;/', '', strip_tags($data['text'])), 0, 200);
            }
            $data['faid']=session('uid');
            if (ShuomingModel::create($data)) {
                return '<script>alert("你好，添加成功了！");parent.location.reload()</script>';
            } else {
                return view_e('添加失败了');
            }
        }
        return view('shuoming/add');
    }
    public function edit(Request $request)
    {
        if (request()->method()=='POST') {
            $data=$request->post();
            $validate = new \app\manage\validate\ShuomingValidate;
            if (!$validate->scene('edit')->check($data)) {
                return view_e($validate->getError());
            }
            if (!isset($data['is_tui'])) {
                $data['is_tui']=0;
            } else {
                $data['is_tui']=1;
            }
            if ($data['create_time']) {
                $data['create_time']=strtotime($data['create_time']);
            }else{
                unset($data['create_time']);
            }
            if ($data['desc']=='') {
                $data['desc']=mb_substr(preg_replace('/\&nbsp;/', '', strip_tags($data['text'])), 0, 200);
            }
            $file = $request->file('pic');
            if ($file && $file->isValid()  && $file->getSize() >0) {
                if(!in_array($file->getUploadExtension(), ['jpg','png','gif','webp','jpeg'])){return view_e('图片格式不正确');}
                if($file->getSize() > 5*1024*1024){return view_e('图片大小不能超过5M');}
                $path = '/shuoming/'.date("YmdHis").rand(10000,99999).session('uid', '0').'.'.$file->getUploadExtension();
                $file->move(public_path().$path);
                $data['pic']=$path;
            } else {
                if (isset($data['ti'])) {
                    preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $data["text"], $arr);
                    foreach ($arr[1] as $k=>$v) {
                        if (substr($v, 0, 4)!='http' and substr($v, 0, 2)!='//' and is_file(substr($v, 1))) {
                            $newarr=getimagesize(substr($v, 1));
                            if ($newarr[0] >100 and $newarr[1] >100) {
                                //图片转移位置
                                if (!is_dir("storage/shuoming/".date("Ymd"))) {
                                    mkdir("storage/shuoming/".date("Ymd"));
                                }
                                $newwei="storage/shuoming/".date("Ymd").'/'.basename(substr($v, 1));
                                $wo=copy(substr($v, 1), $newwei);
                                if ($wo) {
                                    $data['pic']='/'.$newwei;
                                }
                                break;
                            }
                        }
                    }
                }
            }
            $config=Db::name('config')->column('value', 'key');
			preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $data["text"], $arr);
			foreach ($arr[1] as $k=>$v) {
			    if (substr($v, 0, 4)!='http' and substr($v, 0, 2)!='//' and is_file(substr($v, 1))) {
			        $newarr=getimagesize(substr($v, 1));
				   if ($config["is_ya"] ==1 and $newarr[0] >$config["ya_w"]) {
				      $image = \think\Image::open(substr($v, 1));
				      $h=$config["ya_w"]*$newarr[1]/$newarr[0];
				      $image->thumb($config['ya_w'],$h)->save(substr($v, 1));
				   }
			    }
			}
            //设置缩率图
            if ($config['thumbnail']==1 and isset($data['pic'])) {
                $image = \think\Image::open(substr($data['pic'], 1));
                //计算配置项
                if (!$config['t_w']) {
                    $config['t_w']=300;
                }
                if (!$config['t_h']) {
                    $config['t_h']=$config['t_w'];
                }
                $image->thumb($config['t_w'], $config['t_h'])->save(substr($data['pic'], 1));
            }
            //添加水印
            if ($config['watermark']==1) {
                preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $data["text"], $arr1);
                foreach ($arr1[1] as $k=>$v) {
                    if (substr($v, 0, 4)!='http' and substr($v, 0, 2)!='//') {
                        $image = \think\Image::open(substr($v, 1));
                        $image->text($config['shui_neirong'], dirname(__FILE__).'/FZXBSJW.TTF', $config['shui_zihao'], $config['shui_yanse'], $config['shui_weizhi'], -15)->save(substr($v, 1));
                    }
                }
            }
            $res=ShuomingModel::update($data, ['id' => $data['id']]);
            if ($res) {
                return view_s('修改成功', url('shuoming/index',['st'=>1]));
            } else {
                return view_e('修改失败了');
            }
        }
        $cid=$request->input('id',0);
        $data=Db::name('shuoming')->where('id', $cid)->find();
        View::assign('data', $data);
        return view('shuoming/edit');
    }
}
